package com.huabo.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * Created by Jackie Liu on 2017/9/25.
 */
public class FormatUtils {

    /**
     * 将字符串text中由openToken和closeToken组成的占位符依次替换为args数组中的值
     *
     * @param openToken
     * @param closeToken
     * @param text
     * @param args
     * @return
     */
    public static String parse(String openToken, String closeToken, String text, Object... args) {
        if (args == null || args.length <= 0) {
            return text;
        }
        int argsIndex = 0;

        if (text == null || text.isEmpty()) {
            return "";
        }
        char[] src = text.toCharArray();
        int offset = 0;
        // search open token
        int start = text.indexOf(openToken, offset);
        if (start == -1) {
            return text;
        }
        final StringBuilder builder = new StringBuilder();
        StringBuilder expression = null;
        while (start > -1) {
            if (start > 0 && src[start - 1] == '\\') {
                // this open token is escaped. remove the backslash and continue.
                builder.append(src, offset, start - offset - 1).append(openToken);
                offset = start + openToken.length();
            } else {
                // found open token. let's search close token.
                if (expression == null) {
                    expression = new StringBuilder();
                } else {
                    expression.setLength(0);
                }
                builder.append(src, offset, start - offset);
                offset = start + openToken.length();
                int end = text.indexOf(closeToken, offset);
                while (end > -1) {
                    if (end > offset && src[end - 1] == '\\') {
                        // this close token is escaped. remove the backslash and continue.
                        expression.append(src, offset, end - offset - 1).append(closeToken);
                        offset = end + closeToken.length();
                        end = text.indexOf(closeToken, offset);
                    } else {
                        expression.append(src, offset, end - offset);
                        offset = end + closeToken.length();
                        break;
                    }
                }
                if (end == -1) {
                    // close token was not found.
                    builder.append(src, start, src.length - start);
                    offset = src.length;
                } else {
                    ///////////////////////////////////////仅仅修改了该else分支下的个别行代码////////////////////////

                    String value = (argsIndex <= args.length - 1) ?
                            (args[argsIndex] == null ? "" : args[argsIndex].toString()) : expression.toString();
                    builder.append(value);
                    offset = end + closeToken.length();
                    argsIndex++;
                    ////////////////////////////////////////////////////////////////////////////////////////////////
                }
            }
            start = text.indexOf(openToken, offset);
        }
        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }
        return builder.toString();
    }

    public static String parse(String text, String[] args) {
        return parse("{", "}", text, args);
    }

    /**
     * 格式化字符串，例如:
     * String result = FormatUtils.formatCharSequence("我叫{0}，住在{2}", "张三", "合肥");
     * @param cs 需要格式化的字符串
     * @param args 替换参数
     * @return
     */
    public static String formatCharSequence(String cs, String... args) {
        if (StringUtils.isBlank(cs) || args.length == 0) {
            return cs;
        }
        StringBuilder stringBuilder = new StringBuilder();
        String result = cs;
        for (int i = 0; i < args.length; i++) {
            stringBuilder.append("{").append(i).append("}");
            result = result.replaceAll(stringBuilder.toString(), args[i]);
            stringBuilder.delete(0, stringBuilder.length());
        }
        return result;
    }

    /**
     * 格式化字符串，例如:
     * Map<String, String> argsMap = new HashMap<String, String>();
     * argsMap.put("name", "张三");
     * argsMap.put("addr", "合肥");
     * String result = FormatUtils.formatCharSequence("我叫{name}，住在{addr}", argsMap);
     * @param cs 需要格式化的字符串
     * @param valueMap 替换参数
     * @return
     */
    public static String formatCharSequence(String cs, Map<String, String> valueMap) {
        if (StringUtils.isBlank(cs) || valueMap == null || valueMap.size() == 0) {
            return cs;
        }
        StringBuilder stringBuilder = new StringBuilder();
        String result = cs;
        for (Map.Entry<String, String> entry : valueMap.entrySet()) {
            stringBuilder.append("{").append(entry.getKey()).append("}");
            result = result.replaceAll(stringBuilder.toString(), entry.getValue());
            stringBuilder.delete(0, stringBuilder.length());
        }
        return result;
    }

    /**
     * 格式化字符串，例如:
     * String result = FormatUtils.formatCharSequence("我叫{name}，住在{addr}", new String[]{"name", "addr"}, new String[]{"张三", "合肥"});
     * @param cs 需要格式化的字符串
     * @param nameArray 格式化名称
     * @param valueArray 替换参数
     * @return
     */
    public static String formatCharSequence(String cs, String[] nameArray, String[] valueArray) {
        if (StringUtils.isBlank(cs) || nameArray == null ||
                valueArray == null || nameArray.length == 0 || valueArray.length == 0) {
            return cs;
        }
        if (nameArray.length > valueArray.length) {
            throw new IllegalArgumentException(String.format("nameArray.length > valueArray.length"));
        }
        StringBuilder stringBuilder = new StringBuilder();
        String result = cs;
        for (int i = 0; i < nameArray.length; i++) {
            stringBuilder.append("{").append(nameArray[i]).append("}");
            result = result.replaceAll(stringBuilder.toString(), valueArray[i]);
            stringBuilder.delete(0, stringBuilder.length());
        }
        return result;
    }
}
